<!--
 * @description 新建/编辑自定义页面
 * @author dumeng
 * @date 2022/10/20
 -->
<template>
  <div class="custom-page-manage-page">
    <div class="custom-page-manage-title">新建/编辑{{ pageType === '1' ? '页面' : '接口' }}</div>
    <template v-if="pageType==='1'">
      <section v-loading="submitloading" class="custom-page-manage-main">
        <el-form
          ref="form"
          v-loading="submitloading"
          :model="form"
          :rules="addRules"
          class="form"
          label-position="right"
          label-width="80px"
          style="height:410px"
        >
          <el-form-item label="页面名称" prop="pageName">
            <el-input v-model.trim="form.pageName" :disabled="pt==='look'" placeholder="请输入页面名称" />
          </el-form-item>
          <el-form-item label="页面标识" prop="pageCode">
            <el-input v-model.trim="form.pageCode" :disabled="pt==='look' || pt==='u'" placeholder="请输入页面标识" />
          </el-form-item>
          <el-form-item label="页面路由" prop="pageRoute">
            <el-input v-model.trim="form.pageRoute" :disabled="pt==='look'" placeholder="请输入页面路由" />
          </el-form-item>
          <el-form-item label="页面参数">
            <el-table
              :data="paramData"
              style="width: 600px;"
            >
              <el-table-column
                label="参数说明"
                width="180"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyName" :disabled="pt==='look'" placeholder="请输入说明" />
                </template>
              </el-table-column>
              <el-table-column
                label="参数名"
                width="180"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyCode" :disabled="pt==='look'" placeholder="请输入参数名" />
                </template>
              </el-table-column>
              <el-table-column v-if="pt!=='look'" label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDelete(scope.$index, scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column v-if="pt!=='look'">
                <template slot="header" slot-scope="scope">
                  <i style="color: red;cursor: pointer;" class="el-icon-circle-plus" @click="addParam" />
                  <span style="color: red;cursor: pointer;" @click="addParam">添加</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="页面说明" prop="descText">
            <el-input
              v-model="form.descText"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 6}"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-form>
      </section>
    </template>
    <template v-else-if="pageType==='2'">
      <section v-loading="submitloading" class="custom-page-manage-main">
        <el-form
          ref="form"
          v-loading="submitloading"
          :model="form"
          :rules="addRules"
          class="form"
          label-position="right"
          label-width="80px"
          style="height:410px"
        >
          <el-form-item label="接口名称" prop="pageName">
            <el-input v-model.trim="form.pageName" :disabled="pt==='look'" placeholder="请输入接口名称" />
          </el-form-item>
          <el-form-item label="接口地址" prop="pageRoute">
            <el-input v-model.trim="form.pageRoute" :disabled="pt==='look'" placeholder="请输入接口地址" />
          </el-form-item>
          <el-form-item label="接口参数">
            <el-table
              :data="paramData"
              style="width: 600px;"
            >
              <el-table-column
                label="参数说明"
                width="180"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyName" :disabled="pt==='look'" placeholder="请输入说明" />
                </template>
              </el-table-column>
              <el-table-column
                label="参数名"
                width="180"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyCode" :disabled="pt==='look'" placeholder="请输入参数名" />
                </template>
              </el-table-column>
              <el-table-column v-if="pt!=='look'" label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDelete(scope.$index, scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column v-if="pt!=='look'">
                <template slot="header" slot-scope="scope">
                  <i style="color: red;cursor: pointer;" class="el-icon-circle-plus" @click="addParam" />
                  <span style="color: red;cursor: pointer;" @click="addParam">添加</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="关联组件" prop="idList">
            <template v-if="form.comName.length!==0">
              <el-tag
                v-for="(tag,i) in form.comName"
                :key="i"
                style="margin:0 20px 20px 0;"
                closable
                type="danger"
                @close="closeTag(i)"
              >
                {{ tag }}
              </el-tag>
            </template>
            <el-button size="mini" type="primary" @click="visible4Choose=true;">选择组件</el-button>
          </el-form-item>
          <el-form-item label="接口描述">
            <el-input v-model.trim="form.descText" :disabled="pt==='look'" placeholder="请输入接口描述" />
          </el-form-item>
        </el-form>
      </section>
    </template>

    <section class="custom-page-manage-footer">
      <el-button style="padding: 10px 30px;" @click="handleCancel">取 消</el-button>
      <el-button v-if="pt!=='look'" type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>

    <!--选择组件-->
    <el-dialog
      :close-on-click-modal="false"
      custom-class="live-dialog"
      :visible.sync="visible4Choose"
      title="选择组件"
      width="970px"
      center
    >
      <choose-comm v-if="visible4Choose" @select="handleSelect" />
      <div slot="footer" class="dialog-footer">
        <el-button
          type="default"
          style="padding: 10px 30px"
          @click="visible4Choose = false"
        >取 消
        </el-button>
        <el-button
          type="primary"
          @click="handelsetChooseData()"
        >确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { get, insert, update } from '../api/register'
import ChooseComm from '@/views/pagemanage/components/chooseComm'

export default {
  name: 'PageManage',
  components: { ChooseComm },
  data() {
    return {
      visible4Choose: false,
      state: 'create',
      classifyOptions: [],
      form: {
        id: '',
        pageName: '',
        pageCode: '',
        pageRoute: '',
        pageParam: '',
        descText: '',
        registerType: '',
        idList: [],
        comName: []
      },
      submitloading: false,
      addRules: {
        pageName: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        pageCode: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        pageRoute: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        pageParam: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        idList: [
          { required: true, message: '请选择关联组件', trigger: 'change' }
        ]
      },
      pageType: '1', // 1:页面登记 2：接口登记
      list: [], // 所有的组件
      props: {
        multiple: true,
        value: 'id',
        label: 'componentName',
        children: 'list'
      },
      pt: '',
      paramData: [],
      chooseData: []// 选择的组件
    }
  },
  created() {
    if (this.$route.query.t === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.handleCancel()
          }
        })
        return
      }
    }
    this.pt = this.$route.query.t
    this.state = this.$route.query.t === 'u' ? 'update' : 'create'
    this.pageType = this.$route.query.pt || '1'
    if (this.$route.query.t !== 'c') {
      this.getData(this.$route.query.i)
    }
  },
  methods: {
    closeTag(i) {
      this.form.idList.splice(i, 1)
      this.form.comName.splice(i, 1)
    },
    handleSelect(val) {
      const arr = val.filter(a => {
        return this.form.idList.indexOf(a.id) === -1
      })
      this.chooseData = arr
    },
    handelsetChooseData() {
      const ids = this.chooseData.map((a) => {
        return a.id
      })
      this.form.idList = this.form.idList.concat(ids)
      const names = this.chooseData.map((a) => {
        return a.componentName
      })
      this.form.comName = this.form.comName.concat(names)
      this.visible4Choose = false
      this.$refs['form'].validateField('idList', (val) => {
        if (!val) {
          return true
        } else {
          return false
        }
      })
    },
    /**
     * 添加参数
     * */
    addParam() {
      this.paramData.push({ keyName: '', keyCode: '' })
    },
    handleDelete(index, row) {
      this.paramData.splice(index, 1)
    },
    handleCancel() {
      this.$router.replace({ path: '/pagemanage/register' })
    },
    onSubmint() {
      if (this.state === 'create') {
        this.createData()
      } else {
        this.updateData()
      }
    },
    createData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)

          params.pageParam = JSON.stringify(this.paramData)
          params.registerType = this.pageType
          if (this.pageType === '2') {
            params.idList = this.form.idList.join(',')
            params.comName = this.form.comName.join(',')
          } else {
            delete params['idList']
            delete params['comName']
          }
          if (this.$route.query.t === 'copy') {
            delete params['id']
          }
          insert(params).then(res => {
            loading.close()
            this.$message.success('创建成功！')
            this.handleCancel()
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            loading.close()
          })
        }
      })
    },
    updateData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params.pageParam = JSON.stringify(this.paramData)
          params.registerType = this.pageType
          if (this.pageType === '2') {
            params.idList = this.form.idList.join(',')
            params.comName = this.form.comName.join(',')
          } else {
            delete params['idList']
            delete params['comName']
          }
          update(params)
            .then(res => {
              loading.close()
              this.$message.success('编辑成功！')
              this.handleCancel()
            })
          // eslint-disable-next-line handle-callback-err
            .catch(err => {
              loading.close()
            })
        }
      })
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if ((key === 'idList' || key === 'comName') && data[key]) {
              try {
                this.form[key] = data[key].split(',')
              } catch (e) {
                this.form[key] = []
              }
            } else {
              this.form[key] = data[key]
              if (key === 'pageParam') {
                try {
                  this.paramData = JSON.parse(data[key])
                } catch (e) {
                  this.paramData = []
                }
              }
            }
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<style lang="scss">
.custom-page-manage-page {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .custom-page-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .custom-page-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: auto;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .form-item-keepalive {
        margin-bottom: 10px;

        .el-icon-circle-close, .el-icon-circle-plus-outline {
          font-size: 20px;
          color: #999;
          margin-left: 10px;
          cursor: pointer;
        }
      }
    }
  }

  .custom-page-manage-footer {
    position: absolute;
    height: 40px;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
